<template>
  <div class="user-table">
    <div class="table-header">
      <span>用户列表</span>
      <div class="header-actions">
        <span v-if="loading" class="loading-text">加载中...</span>
        <span v-else-if="data.length > 0" class="total-text">共 {{ total }} 人</span>
        <el-button link type="primary" @click="handleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </el-button>
      </div>
    </div>
    <div class="search-bar">
      <el-input
        v-model="searchForm.username"
        class="search-input"
        clearable
        placeholder="请输入用户名"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><user /></el-icon>
        </template>
      </el-input>
      <el-input
        v-model="searchForm.mobile"
        class="search-input"
        clearable
        placeholder="请输入手机号"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><phone /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>
    <div v-if="data.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无用户数据" />
    </div>
    <el-table v-else ref="tableRef" v-loading="loading" :data="data" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="姓名" min-width="120">
        <template #default="{ row }">
          <div class="user-cell">
            <el-avatar class="user-avatar" size="small">
              {{ row.name ? row.name.substring(0, 1) : 'U' }}
            </el-avatar>
            <span class="user-name">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="150" prop="mobile" show-overflow-tooltip />
      <el-table-column label="账号" min-width="120" prop="username" show-overflow-tooltip />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleSelect(row)">添加</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPageProxy"
        v-model:page-size="pageSizeProxy"
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Phone } from '@element-plus/icons-vue'
import type { ElTable } from 'element-plus'
import { computed, ref } from 'vue'
import type { User as UserType } from './types'

const props = defineProps({
  data: {
    type: Array as () => UserType[],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  currentPage: {
    type: Number,
    default: 1,
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  total: {
    type: Number,
    default: 0,
  },
})

const emit = defineEmits(['selection-change', 'page-change', 'select-user', 'search'])

// 搜索表单
const searchForm = ref({
  username: '',
  mobile: '',
})

// 搜索处理
const handleSearch = () => {
  emit('page-change', {
    page: 1,
    pageSize: props.pageSize,
    ...searchForm.value,
  })
}

// 双向绑定分页参数的代理
const currentPageProxy = computed({
  get: () => props.currentPage,
  set: (val) => emit('page-change', { page: val, pageSize: props.pageSize }),
})

const pageSizeProxy = computed({
  get: () => props.pageSize,
  set: (val) => emit('page-change', { page: props.currentPage, pageSize: val }),
})

// 状态管理
const isAllSelected = ref(false)
const selectedRows = ref<UserType[]>([])
const tableRef = ref<InstanceType<typeof ElTable>>()

// 表格选择变化
const handleSelectionChange = (selection: UserType[]) => {
  selectedRows.value = selection
  isAllSelected.value = selection.length === props.data.length && props.data.length > 0
  emit('selection-change', selection)
}

// 全选/取消全选
const handleSelectAll = () => {
  if (isAllSelected.value) {
    tableRef.value?.clearSelection()
  } else {
    tableRef.value?.toggleAllSelection()
  }
}

// 手动选择一行
const handleSelect = (row: UserType) => {
  emit('select-user', row)
}

// 分页处理
const handleSizeChange = (val: number) => {
  emit('page-change', {
    page: props.currentPage,
    pageSize: val,
    ...searchForm.value,
  })
}

const handleCurrentChange = (val: number) => {
  emit('page-change', {
    page: val,
    pageSize: props.pageSize,
    ...searchForm.value,
  })
}

// 暴露方法给父组件
defineExpose({
  clearSelection: () => tableRef.value?.clearSelection(),
  toggleAllSelection: () => tableRef.value?.toggleAllSelection(),
  unselectRow: (userId: string) => {
    const rowIndex = props.data.findIndex((item) => item.id === userId)
    if (rowIndex !== -1) {
      tableRef.value?.toggleRowSelection(props.data[rowIndex], false)
    }
  },
})
</script>

<style scoped>
.user-table {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
  background-color: #fff;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  font-weight: 500;
  border-bottom: 1px solid #ebeef5;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.loading-text,
.total-text {
  font-size: 13px;
  font-weight: normal;
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

.user-cell {
  display: flex;
  gap: 8px;
  align-items: center;
}

.user-avatar {
  color: #fff;
  background-color: #409eff;
}

.user-name {
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.search-bar {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.search-input {
  width: 200px;
}
</style>
